#include"Socket.hpp"
#include"Parser.hpp"
#include<memory>

void Usage(std::string proc)
{
    std::cerr << "Usage: "<< proc << " serverip serverport" <<std::endl; 
}

//
int main(int argc , char* argv[])
{
    if(argc !=3)
    {
        Usage("argv[0]");
        return 0;
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    //创建套接字
    std::unique_ptr<Socket> sockfd = std::make_unique<TcpSocket>();
    sockfd->BuildTcpSocketClient();
    //向服务器发起连接请求
    InetAddr server(serverport , serverip);
   if(sockfd->Connect(server)==false) return 0;
   std::string outbuffer;
   //与服务器成功连接
   while(true)
   {
        Request req;//创建请求
        std::cout << "Please enter X: ";
        std::cin >>  req._x;
        std::cout << "Please enter Y: ";
        std::cin >>  req._y;
        std::cout << "Please enter Oper: ";
        std::cin >>  req._oper;

        //序列化
        std::string jsonstr;
        req.Serialize(&jsonstr);

        //将请求打包
        std::string req_str = Protocol::Package(jsonstr);

        //debug
        std::cout << "req_str: "<< req_str <<std::endl;

        //发送给服务器
        ssize_t n = sockfd->Send(req_str);
        if(n>0)
        {
            //发送成功，从服务器端获取应答
            Responce resp;
            std::string resp_str; 
            ssize_t m = sockfd->Recv(&resp_str);
            outbuffer+=resp_str;
            if(m > 0)
            {
                //解包
                std::string jsonstr;
                Protocol::Unpack(outbuffer ,&jsonstr);
                //反序列
                bool r  = resp.UnSerialize(jsonstr);
                //debug
                if(r) resp.Print();
            }
        }
   }
    return 0;
}